window.fbAsyncInit = function () {
    FB.init({
        appId: '150800278297282',
        status: true, // check login status
        cookie: true, // enable cookies to allow the server to access the session
        xfbml: true  // parse XFBML
    });
    ShowHideFBControls();
    //subscribing to session change event
    FB.Event.subscribe('auth.sessionChange', function (response) {
        // do something with response.session
    });
    //subscribing to login event
    FB.Event.subscribe('auth.login', function (response) {
        ShowHideFBControls();
    });
    //subscribing to logout event
    FB.Event.subscribe('auth.logout', function (response) {
        ShowHideFBControls();
    });
};

function LoadFbJsSdk() {
    var e = document.createElement('script');
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
    e.async = true;
    document.getElementById('fb-root').appendChild(e);
}

function ShowHideFBControls() {
    if (FB != null) {
        FB.getLoginStatus(function (response) {
            if (response.status == "connected") {
                $('#fbLoginDiv').hide();
                $('#fbLogonDiv').show();
                FB.api('/me', function (user) {
                    if (user != null) {
                        var image = document.getElementById('fbLogonDivProfilePic');
                        image.src = 'http://graph.facebook.com/' + user.id + '/picture';
                        var name = document.getElementById('fbLogonDivUserName');
                        name.innerHTML = user.name
                    }
                });
            }
            else {
                $('#fbLoginDiv').show();
                $('#fbLogonDiv').hide();
            }

            if (response.session) {
                //alert("Logedin");
            } else {
                //alert("not loged in");
            }
        });
    }
}

function CallFBLogout() {
    FB.logout(function (response) {
        ShowHideFBControls();
    });

}

function CallFBLoginPopup() {
    if (FB != null) {
        FB.login(function (response) {
            if (response.session) {
                if (response.perms) {
                    // user is logged in and granted some permissions.
                    // perms is a comma separated list of granted permissions
                } else {
                    // user is logged in, but did not grant any permissions
                }
                //window.location.href = "/pages/FB/FBLogon.ashx?returnUrl=" + window.location.href;
                $.get("/pages/FB/Facebook.ashx", { pblogon: "1" },
                            function (data) {
                                //todo
                            });
            } else {
                // user is not logged in
            }
        });

    }
}

function FBCallMeApi() {
    FB.getLoginStatus(function (response) {
        if (response.status == "connected") {

            FB.api('/me', function (user) {
                if (user != null) {
                    var image = document.getElementById('fbLogonDivProfilePic');
                    image.src = 'http://graph.facebook.com/' + user.id + '/picture';
                    var name = document.getElementById('fbLogonDivUserName');
                    name.innerHTML = user.name
                }
            });

        }
        else {

        }


    });

}

/*************************************************
*   Async JavaScript File Loader                 *
**************************************************/

function LoadJSFile(fileName) {
    var scriptTag = document.createElement('script');
    scriptTag.type = 'text/javascript';
    scriptTag.async = true;
    scriptTag.src = fileName;
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(scriptTag, s);
}

/*************************************************
*   String Utilites                              *
**************************************************/
function stripHTML(originalStr) {

    stripHTML(originalStr, "");
}

function stripHTML(originalStr, replacerStr) {
    var regex = /<\S[^><]*>/g;
    return originalStr.replace(regex, replacerStr);
}

function isValidEmail(sText) {
    var regexEmail = /^(?:\w+\.?)*\w+@(?:\w+\.)+\w+$/;
    return regexEmail.test(sText);
}

function isValidUrl(originalStr) {
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    return regexp.test(originalStr);
}

function isEmpty(text) {
    var editorTextLength = text.replace(/\s+|\n+|\t+/g, "").length;
    return editorTextLength == 0;
}

function StripHTMLAndTrim(text) {
    var htmlStriper = /<(?:.|\s)*?>/g;
    text = text.replace(htmlStriper, " ");
    while (text.indexOf("  ") >= 0) {
        text = text.replace("  ", " ");
    }
    return text.replace(/^\s+|\s+$/g, "");
}

/* String Trim Utilites *********************/

String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, "");
}
String.prototype.ltrim = function () {
    return this.replace(/^\s+/, "");
}
String.prototype.rtrim = function () {
    return this.replace(/\s+$/, "");
}

/* String.Format Utilites *********************/
String.format = function (text) {

    //check if there are two arguments in the arguments list
    if (arguments.length <= 1) {
        //if there are not 2 or more arguments there's nothing to replace
        //just return the original text
        return text;
    }

    //decrement to move to the second argument in the array
    var tokenCount = arguments.length - 2;
    for (var token = 0; token <= tokenCount; token++) {
        //iterate through the tokens and replace their placeholders from the original text in order
        text = text.replace(new RegExp("\\{" + token + "\\}", "gi"),
                                                arguments[token + 1]);
    }
    return text;
};

String.prototype.format = function () {
    var txt = this;
    for (var i = 0; i < arguments.length; i++) {
        var exp = new RegExp('\\{' + (i) + '\\}', 'gm');
        txt = txt.replace(exp, arguments[i]);
    }
    return txt;
}
/*************************************************
*   Cookie Utilities                             *
**************************************************/
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ')
            c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0)
            return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

/*************************************************
*   HTTP Request Utilites                        *
**************************************************/
function GetHttpRequestObject() {

    var xmlhttp = false;

    try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {
            xmlhttp = false;
        }
    }

    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
        try {
            xmlhttp = new XMLHttpRequest();
        } catch (e) {
            xmlhttp = false;
        }
    }
    if (!xmlhttp && window.createRequest) {
        try {
            xmlhttp = window.createRequest();
        } catch (e) {
            xmlhttp = false;
        }
    }
    return xmlhttp;
}
/*************************************************
*   General JS Utils                             *
**************************************************/

function GetElementValue(eid) {
    return document.getElementById(eid).value;
}

function SetElementValue(eid, val) {
    document.getElementById(eid).value = val;
}

/*************************************************
*   Script Injection for JSON                    *
**************************************************/

function injectScript(url) {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    head.appendChild(script);
}

function getMetaContents(meta_name) {
    var my_arr = document.getElementsByTagName("META");
    for (var counter = 0; counter < my_arr.length; counter++) {
        if (my_arr[counter].name.toLowerCase() == meta_name.toLowerCase()) {
            return my_arr[counter].content;
        }
    }
    return "";
}


/*************************************************
*   PBDesk.com CMS utilities                     *
**************************************************/
function DoArticleRedirect(extUrl) {
    if (extUrl.length > 0) {
        window.open(extUrl, "pbdesk.com-art");
        window.location.href = "/";
    }
}
/****************** Javascript Utility Library (Version 1.0) 01/Dec/2010 *****************/
